<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-input style="width: 280px;" v-model="find_data.find" placeholder="用户姓名/电话（支持模糊查询）" clearable
                        prefix-icon="Search" />
                    <el-date-picker :default-time="defaultTime" style="width: 350px;margin-left:10px;"
                        v-model="data_time" @change="datetime_btn" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                    <el-select v-model="find_data.discountWay" placeholder="列表类型" clearable
                        style="width: 140px;margin-left:10px;">
                        <el-option label="全部-列表类型" value=""></el-option>
                        <el-option label="领取列表" value="0"></el-option>
                        <el-option label="设置列表" value="1"></el-option>
                    </el-select>
                    <el-select v-model="find_data.useState" placeholder="使用状态" clearable
                        style="width: 140px;margin-left:10px;">
                        <el-option label="全部-使用状态" value=""></el-option>
                        <el-option label="使用完成" value="-2"></el-option>
                        <el-option label="已失效" value="-1"></el-option>
                        <el-option label="未使用" value="0"></el-option>
                    </el-select>
                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">添加</el-button>
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'useState'" #="{ row, column, $index }">
                                <span>{{ row.useState == '' ? '全部-使用状态' : row.useState == '-2' ? '使用完成' : row.useState
                                    ==
                                    '-1' ? '已失效' : row.useState == '0' ? '未使用' : '无' }}</span>
                            </template>
                            <template v-if="item.field == 'provideStart'" #="{ row, column, $index }">
                                <div>开始：{{ row.provideStart }}</div>
                                <div>截止：{{ row.provideEnd }}</div>
                            </template>

                            <template v-if="item.field == 'receiptStart'" #="{ row, column, $index }">
                                <div v-if="row.receiptStart">
                                    <div>开始：{{ row.receiptStart }}</div>
                                    <div>截止：{{ row.receiptEnd }}</div>
                                </div>
                                <span v-else>自领取之日<b style="color:red">{{ row.validDay }}天</b>内有效</span>
                            </template>
                            <template v-if="item.field == 'validScene'" #="{ row, column, $index }">
                                <span>{{ row.validScene == '1' ? '单程接送' : row.validScene == '2' ? '旅游包车' :
                                    row.validScene ==
                                        '3' ? '顺风车' : '无' }}
                                    <span style="color:red">{{ row.validSeats.replace(',', '座、') }}座</span>
                                </span>
                            </template>
                            <template v-if="item.field == 'giveWay'" #="{ row, column, $index }">
                                <span>{{ row.giveWay == 'NEWPERSON' ? '新人发放' : row.giveWay == 'PAYORDER' ? '下单发放' : ''
                                    }}</span>
                            </template>
                            <template v-if="item.field == 'validWay'" #="{ row, column, $index }">
                                <span>{{ row.validWay == '1' ? '全额抵扣' : row.validWay == '2' ? '按订单比例' : row.validWay ==
                                    '3' ? '按优惠券比例' : '无' }}</span>
                            </template>
                            <template v-if="item.field == 'validCustomer'" #="{ row, column, $index }">
                                <span>{{ row.validCustomer == '1' ? '任意客户' : row.validCustomer == '2' ? '下单成功客户' :
                                    row.validCustomer ==
                                        '3' ? '按客户星级级别' : '无' }}</span>
                            </template>
                            <template v-if="item.field == 'sharePopular'" #="{ row, column, $index }">
                                <span style="color:red" v-if="row.sharePopular == 1">参加</span>
                                <span style="color:red" v-if="row.sharePopular == 2">不参加</span>
                                分享推广
                            </template>

                            <template v-if="item.field == 'highMoney'" #="{ row, column, $index }">
                                <span style="color:red">{{ row.highMoney }}</span>元
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="45%" :close-on-click-modal='false'>
            <el-form ref="adupCouponSetFm" :model="add_data" label-width="110px" label-suffix="：">
                <el-form-item label="优惠券名称" prop="discountName" required
                    :rules="[{ required: true, message: '优惠券名称不能为空', trigger: ['blur', 'change'] }]">
                    <el-input v-model="add_data.discountName" placeholder="请填写优惠券名称" maxlength="20" show-word-limit
                        style="width: 505px;">
                    </el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="下单方式" prop="addOrderWay" required
                            :rules="[{ required: true, message: '下单方式不能为空', trigger: ['blur', 'change'] }]">
                            <el-select v-model="add_data.addOrderWay" placeholder="请选择下单方式" style="width: 170px;">
                                <el-option label="全部订单" value="PCALL"></el-option>
                                <el-option label="前台订单" value="PCHOME"></el-option>
                                <el-option label="后台订单" value="PCTEAM"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="14">
                        <el-form-item label="领取有效期" prop="provideEnd" required
                            :rules="[{ required: true, message: '领取有效期起止日期不能为空', trigger: ['blur', 'change'] }]">
                            <el-date-picker :default-time="[
                                new Date(2000, 1, 1, 0, 0, 0),
                                new Date(2000, 2, 1, 23, 59, 59),
                            ]" v-model="add_data_provide" @change="add_data_provide_btn" type="datetimerange"
                                start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="使用场景" prop="validScene" required
                            :rules="[{ required: true, message: '使用场景不能为空', trigger: ['blur', 'change'] }]">
                            <el-select v-model="add_data.validScene" placeholder="请选择使用场景" style="width: 170px">
                                <el-option label="单程接送" value="1"></el-option>
                                <el-option label="旅游包车" value="2"></el-option>
                                <el-option label="顺风车" value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="使用车型" prop="validSeats" required
                            :rules="[{ type: 'array', required: true, message: '使用车型不能为空', trigger: ['blur', 'change'] }]">
                            <el-select v-model="add_data.validSeats" multiple collapse-tags :filterable="false"
                                placeholder="请选择使用车型" style="width: 200px;">
                                <el-option label="5座" value="5"></el-option>
                                <el-option label="7座" value="7"></el-option>
                                <el-option label="9座" value="9"></el-option>
                                <el-option label="12座" value="12"></el-option>
                                <el-option label="14座" value="14"></el-option>
                                <el-option label="17座" value="17"></el-option>
                                <el-option label="30座" value="30"></el-option>
                                <el-option label="39座" value="39"></el-option>
                                <el-option label="49座" value="49"></el-option>
                                <el-option label="55座" value="55"></el-option>

                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="分享推广" prop="sharePopular" required
                            :rules="[{ required: true, message: '分享推广不能为空', trigger: ['blur', 'change'] }]">
                            <el-select v-model="add_data.sharePopular" placeholder="请选择分享推广" style="width: 170px">
                                <el-option label="参加分享推广" value="1"></el-option>
                                <el-option label="不参加分享推广" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="适用站点" prop="stationIds" required
                            :rules="[{ type: 'array', required: true, message: '适用站点不能为空', trigger: ['blur', 'change'] }]">
                            <el-select v-model="add_data.stationIds" multiple collapse-tags :filterable="true"
                                placeholder="请选择适用站点" style="width: 250px;">
                                <el-option v-for="it in stationArr" :key="it.id" :label="it.station_name"
                                    :value="it.id">
                                </el-option>
                            </el-select>

                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="使用有效期" required style="margin-bottom: 10px;">
                    <el-row type="flex">
                        <el-form-item prop="receiptType" style="margin-right: 10px;">
                            <el-select v-model="receiptType" placeholder="有效期类型" style="width: 170px;">
                                <el-option label="有效天数" value="1"></el-option>
                                <el-option label="固定时间" value="2"></el-option>
                            </el-select>
                        </el-form-item>

                        <template v-if="receiptType == 1">
                            <span class="fm-item-text">领取后</span>
                            <el-form-item prop="validDay" key="1"
                                :rules="[{ required: true, message: '使用有效天数不能为空', trigger: ['blur', 'change'] }]">
                                <el-input v-model.number="add_data.validDay" type="age" placeholder="有效天数" maxlength="6"
                                    style="width: 210px;">
                                </el-input>
                                <span class="fm-item-text"> 天内有效</span>
                            </el-form-item>
                        </template>

                        <el-form-item key="2" v-if="receiptType == 2" prop="receiptStart" style="margin-left: 10px;"
                            :rules="[{ required: true, message: '使用有效期起止日期不能为空', trigger: ['blur', 'change'] }]">


                            <el-date-picker :default-time="[
                                new Date(2000, 1, 1, 0, 0, 0),
                                new Date(2000, 2, 1, 23, 59, 59),
                            ]" v-model="add_data_receiptStart" @change="add_data_receiptStart_btn" type="datetimerange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="截止日期"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-row>
                </el-form-item>

                <el-form-item label="优惠券金额" required style="margin-bottom: 10px;">
                    <el-row type="flex">
                        <el-form-item prop="validMoney"
                            :rules="[{ required: true, message: '优惠券金额方式不能为空', trigger: ['blur', 'change'] }]">
                            <el-select v-model="add_data.validMoney" placeholder="金额类型"
                                style="width: 170px;margin-right: 10px;">
                                <el-option label="固定金额" value="1"></el-option>
                                <el-option label="随机金额" value="2"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item key="1" v-if="add_data.validMoney == 1" prop="highMoney"
                            :rules="[{ required: true, message: '金额不能为空', trigger: ['blur', 'change'] }]">
                            <el-row type="flex">
                                <el-input oninput="value=value.replace(/[^0-9.]/g,'')" v-model="add_data.highMoney"
                                    placeholder="优惠券金额" maxlength="6" style="width: 325px;">
                                    <template #append>元</template>
                                </el-input>
                            </el-row>
                        </el-form-item>

                        <template v-if="add_data.validMoney == 2">
                            <span style="margin-left: 20px;" class="fm-item-text">金额区间</span>
                            <el-form-item prop="lowMoney" key="2.1"
                                :rules="[{ required: true, message: '最低金额不能为空', trigger: ['blur', 'change'] }]">
                                <el-input oninput="value=value.replace(/[^0-9.]/g,'')" v-model="add_data.lowMoney"
                                    placeholder="最低金额" maxlength="6" style="width: 140px;">
                                    <template #append>元</template>
                                </el-input>
                            </el-form-item>
                            <span style="display: inline-block; padding: 0 8px;">~</span>
                            <el-form-item prop="highMoney" key="2.2"
                                :rules="[{ required: true, message: '最高金额不能为空', trigger: ['blur', 'change'] }]">
                                <el-input oninput="value=value.replace(/[^0-9.]/g,'')" v-model="add_data.highMoney"
                                    placeholder="最高金额" maxlength="6" style="width: 140px;">

                                    <template #append>元</template>
                                </el-input>
                            </el-form-item>
                        </template>
                    </el-row>
                </el-form-item>

                <el-form-item label="使用方式" required style="margin-bottom: 10px">
                    <el-row type="flex">
                        <el-form-item prop="validWay">
                            <el-select v-model="add_data.validWay" placeholder="请选择使用方式" @change="onChangeValidWay"
                                style="width: 170px; margin-right: 10px;">
                                <el-option label="全额抵扣" value="1"></el-option>
                                <el-option label="按订单比例" value="2"></el-option>
                                <el-option label="按优惠券比例" value="3"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="useRatio" v-if="add_data.validWay == 2 || add_data.validWay == 3">
                            <el-input oninput="value=value.replace(/[^0-9.]/g,'')" v-model="add_data.useRatio"
                                placeholder="使用比例" maxlength="6" style="width: 195px; margin-right: 10px;">
                                <template #append>%</template>

                            </el-input>
                        </el-form-item>

                        <el-form-item prop="singleWay">
                            <el-select v-model="add_data.singleWay" placeholder="使用次数" style="width: 120px">
                                <el-option label="单次使用" value="1"></el-option>
                                <el-option label="多次使用" value="2"
                                    v-if="add_data.validWay == 2 || add_data.validWay == 3"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-row>
                </el-form-item>

                <el-form-item label="使用客户" required style="margin-bottom: 10px">
                    <el-row type="flex">
                        <el-form-item prop="validCustomer">
                            <el-select v-model="add_data.validCustomer" placeholder="请选择使用客户"
                                @change="onChangeValidCustomer" style="width: 170px; margin-right: 10px;">
                                <el-option label="任意客户" value="1"></el-option>
                                <el-option label="新客户" value="2"></el-option>
                                <el-option label="下单成功客户" value="3"></el-option>
                                <el-option label="按级别" value="4"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item key="2" v-if="add_data.validCustomer == 2" prop="validCount">
                            <el-input oninput="value=value.replace(/[^0-9]|^0{2,}/g,'')" v-model="add_data.validCount"
                                placeholder="请填写天数" maxlength="6" style="width: 260px;">
                            </el-input>
                            <span class="fm-item-text"> 天未下单</span>
                        </el-form-item>

                        <template v-if="add_data.validCustomer == 3">
                            <el-row type="flex">
                                <el-form-item prop="successStart" key="3.1">
                                    <el-date-picker :default-time="[
                                        new Date(2000, 1, 1, 0, 0, 0),]" type="datetime" v-model="add_data.successStart" :editable="false"
                                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                        placeholder="开始日期" style="width: 200px;">
                                    </el-date-picker>
                                    <span class="fm-item-text">开始</span>
                                </el-form-item>
                                <!-- <el-form-item prop="successStart" key="3.1">
                                    <el-date-picker type="date" v-model="add_data.successStart"
                                        :editable="false" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                                        placeholder="开始日期" style="width: 200px;">
                                    </el-date-picker>
                                    <span class="fm-item-text">开始</span>
                                </el-form-item> -->
                                <el-form-item prop="validCount" key="3.2">
                                    <el-input oninput="value=value.replace(/[^0-9]|^0{2,}/g,'')"
                                        v-model="add_data.validCount" placeholder="订单数" maxlength="4"
                                        style="width: 70px;">
                                    </el-input>
                                    <span class="fm-item-text"> 单内执行</span>
                                </el-form-item>
                            </el-row>
                        </template>

                        <el-form-item key="4" v-if="add_data.validCustomer == 4" prop="validCount">
                            <el-select v-model="add_data.validCount" placeholder="级别" style="width: 325px">
                                <el-option label="1星客户" value="1"></el-option>
                                <el-option label="2星客户" value="2"></el-option>
                                <el-option label="3星客户" value="3"></el-option>
                                <el-option label="4星客户" value="4"></el-option>
                                <el-option label="5星客户" value="5"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-row>


                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="发放方式" prop="giveWay" required>
                            <el-select v-model="add_data.giveWay" placeholder="请选择发放方式" style="width: 170px;">
                                <el-option label="新人发放" value="NEWPERSON"></el-option>
                                <el-option label="下单发放" value="PAYORDER"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">

                    </el-col>
                </el-row>

                <el-row>
                    <el-form-item label="使用规则" prop="note" required
                        :rules="[{ required: true, message: '使用规则不能为空', trigger: ['blur', 'change'] }]">
                        <el-input v-model="add_data.note" type="textarea" placeholder="请填写优惠券使用规则" maxlength="2000"
                            show-word-limit :autosize="{ minRows: 5, maxRows: 30 }" style="width: 505px;">
                        </el-input>
                    </el-form-item>
                </el-row>

            </el-form>
            <el-button @click="ok_btn" style="margin-left:30vw;margin-top:5px" type="primary">确认提交</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import CircularJSON from 'circular-json'
import {
    adupPrivateSet, getPrivateSetList, discountList, findStationCombo, addRouteDiscount, updateRouteDiscount, delRouteDiscount

} from '@/api/discount_coupon_management.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { scopy } from '@/utils/common.js'
onMounted(async () => {
    let discount_coupon_settings = JSON.parse(localStorage.getItem('discount_coupon_settings'))
    if (discount_coupon_settings) {
        data_time.value = [discount_coupon_settings.stime, discount_coupon_settings.etime]
        find_data.find = discount_coupon_settings.find
        find_data.discountWay = discount_coupon_settings.discountWay
        find_data.etime = discount_coupon_settings.etime
        find_data.stime = discount_coupon_settings.stime
        find_data.useState = discount_coupon_settings.useState
    }

    getPrivateSetList({
        find: '优惠卷设置',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })

    findStationCombo({
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        stationTypes: ['AIRPORT', 'TRAIN', 'BUS'],
    }).then(res => {
        stationArr.value = res.data.list
    })
    await list_api()


})

//#region 表格数据处理
const table_data_list = reactive([

    { label: '使用状态', field: 'useState', width: 130, off: true },
    { label: '领取人', field: 'receiptUserName', width: 90, off: true },
    { label: '优惠券名称', field: 'discountName', width: 120, off: true },
    { label: '优惠券编号', field: 'discountNo', width: 160, off: true },
    { label: '领取有效期', field: 'provideStart', width: 230, off: true },
    { label: '使用有效期', field: 'receiptStart', width: 230, off: true },
    { label: '使用场景', field: 'validScene', width: 90, off: true },
    { label: '优惠金额', field: 'highMoney', width: 90, off: true },
    { label: '发放方式', field: 'giveWay', width: 130, off: true },
    { label: '使用方式', field: 'validWay', width: 130, off: true },
    { label: '使用客户', field: 'validCustomer', width: 130, off: true },
    { label: '分享推广', field: 'sharePopular', width: 130, off: true },
    { label: '使用规则', field: 'note', width: 400, off: true },
    { label: '适用站点', field: 'stationNames', width: 220, off: true },
    { label: '添加时间', field: 'addTime', width: 165, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '优惠卷设置',
        tbNum: "discount_coupon_settings",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion


//#region 分页列表
const data_time = ref([])
const datetime_btn = (e, y, c) => {
    if (data_time.value) {
        find_data.stime = data_time.value[0]
        find_data.etime = data_time.value[1]
    } else {
        find_data.stime = ''
        find_data.etime = ''
    }

}
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    find: '',
    discountWay: '1',
    stime: '',
    etime: "",
    useState: "",
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    discountList(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total
    })
}
//#endregion

//#region 添加
const add_off = ref(false)
const add_data_provide = ref([])
const add_data_provide_btn = (e, y, c) => {
    if (add_data_provide.value) {
        add_data.provideStart = add_data_provide.value[0]
        add_data.provideEnd = add_data_provide.value[1]
    } else {
        add_data.provideStart = ''
        add_data.provideEnd = ''
    }

}
const add_data_receiptStart = ref([])
const add_data_receiptStart_btn = (e, y, c) => {
    if (add_data_receiptStart.value) {
        add_data.receiptStart = add_data_receiptStart.value[0]
        add_data.receiptEnd = add_data_receiptStart.value[1]
    } else {
        add_data.receiptStart = ''
        add_data.receiptEnd = ''
    }

}

const stationArr = ref([])
const receiptType = ref('1')
const onChangeValidWay = (e) => {
    if (e == 1) {
        add_data.singleWay = '1'
    }
}
const onChangeValidCustomer = () => {
    add_data.validCount = ''
}

const title = ref('添加优惠卷设置')
const add_data = reactive({
    id: "",
    addOrderWay: "",
    discountName: "",
    giveWay: "NEWPERSON",
    highMoney: "",
    lowMoney: "",
    note: "",
    provideEnd: "",
    provideStart: "",
    receiptEnd: "",
    receiptStart: "",
    sharePopular: "",
    singleWay: "1",
    stationIds: "",
    successStart: "",
    useRatio: "",
    validCount: "",
    validCustomer: "1",
    validDay: "",
    validMoney: "1",
    validScene: "",
    validSeats: "",
    validWay: "1",

})


const add_btn = () => {

    title.value = '添加优惠卷设置'
    add_data.id = ''
    add_data.addOrderWay = ''
    add_data.discountName = ''
    add_data.giveWay = 'NEWPERSON'
    add_data.highMoney = ''
    add_data.lowMoney = ''
    add_data.note = ''
    add_data.provideEnd = ''
    add_data.provideStart = ''
    add_data.receiptEnd = ''
    add_data.receiptStart = ''
    add_data.sharePopular = ''
    add_data.singleWay = '1'
    add_data.stationIds = ''
    add_data.successStart = ''
    add_data.useRatio = ''
    add_data.validCount = ''
    add_data.validCustomer = '1'
    add_data.validDay = ''
    add_data.validMoney = '1'
    add_data.validScene = ''
    add_data.validSeats = ''
    add_data.validWay = '1'

    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }


    title.value = '修改模版基础信息设置'

    add_data.id = table_list.value[0].id
    add_data.addOrderWay = table_list.value[0].addOrderWay
    add_data.discountName = table_list.value[0].discountName
    add_data.giveWay = table_list.value[0].giveWay
    add_data.highMoney = table_list.value[0].highMoney
    add_data.lowMoney = table_list.value[0].lowMoney
    add_data.note = table_list.value[0].note
    add_data.provideEnd =
        add_data.provideStart = table_list.value[0].provideStart
    add_data.receiptEnd = table_list.value[0].receiptEnd
    add_data.receiptStart = table_list.value[0].receiptStart
    add_data.sharePopular = String(table_list.value[0].sharePopular)
    add_data.singleWay = String(table_list.value[0].singleWay)
    add_data.stationIds = table_list.value[0].stationIds.split(',').map(Number)
    add_data.successStart = table_list.value[0].successStart
    add_data.useRatio = table_list.value[0].useRatio * 100
    add_data.validCount = table_list.value[0].validCount
    add_data.validCustomer = String(table_list.value[0].validCustomer)
    add_data.validDay = table_list.value[0].validDay
    add_data.validMoney = String(table_list.value[0].validMoney)
    add_data.validScene = String(table_list.value[0].validScene)
    add_data.validSeats = table_list.value[0].validSeats.split(',')
    add_data.validWay = String(table_list.value[0].validWay)
    add_data_provide.value = [table_list.value[0].provideStart, table_list.value[0].provideEnd]
    add_data_receiptStart.value = [table_list.value[0].receiptStart, table_list.value[0].receiptEnd]
    receiptType.value = table_list.value[0].receiptStart ? '2' : '1'


    add_off.value = true
}
//#endregion

// 提交
const adupCouponSetFm = ref('')
const ok_btn = () => {

    adupCouponSetFm.value.validate((valid) => {
        if (!valid) { return false; } else {
            if (title.value == '添加优惠卷设置') {
                let ps = scopy(add_data)
                ps.provideStart = ps.provideStart + ' ' + '00:00:00'
                ps.provideEnd = ps.provideEnd + ' ' + '00:00:00'
                ps.receiptStart = ps.receiptStart ? ps.receiptStart + ' ' + '00:00:00' : ''
                ps.receiptEnd = ps.receiptEnd ? ps.receiptEnd + ' ' + '00:00:00' : ''
                ps.stationIds = ps.stationIds.join(',')
                ps.validSeats = ps.validSeats.join(',')

                addRouteDiscount(ps).then(res => {
                    if (res.code == 1) {
                        list_api()
                        add_off.value = false
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            } else {
                let ps = scopy(add_data)
                ps.provideStart = ps.provideStart + ' ' + '00:00:00'
                ps.provideEnd = ps.provideEnd + ' ' + '00:00:00'
                ps.receiptStart = ps.receiptStart + ' ' + '00:00:00'
                ps.receiptEnd = ps.receiptEnd + ' ' + '00:00:00'
                ps.stationIds = ps.stationIds.join(',')
                ps.validSeats = ps.validSeats.join(',')

                updateRouteDiscount(ps).then(res => {
                    if (res.code == 1) {
                        list_api()
                        add_off.value = false
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            }
        }

    })



}


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        '是否确认删除优惠卷?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            if (table_list.value[0].templatesInfoId == '基础模版') {
                return ElMessage({
                    message: '基础模版不能删除，只能修改',
                    type: 'warning',
                })
            } else {
                delRouteDiscount({
                    id: table_list.value[0].id
                }).then(res => {
                    if (res.code == 1) {
                        list_api()
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            }



        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {
    localStorage.setItem('discount_coupon_settings', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion
</script>

<style scoped lang='scss'></style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}

.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
